const request     = require('request');
const config      = require('../config/config');
const packageInfo = require('../../package');
const url = require('url');
const crypto = require('crypto');

const staticSource = ['js','css','svg','png','jpg','gif','woff2','woff','ttf'];

const contentType = {
    'js':'application/javascript; charset=utf-8',
    'css':'text/css; charset=utf-8',
    'png':'image/png',
    'jpg':'image/jpeg',
    'webp':'image/webp',
    'svg':'image/svg+xml',
    'woff2':'font/woff2',
    'ttf':'font/ttf'
};

global.browserWSEndpoint = null;

function base64Encode(str){
    return new Buffer(str).toString('base64');
}

function get(url,params,token,callback,errorback){
    request({
        url:config.SERVER.HOST + url + params,
        method:'GET',
        headers:{
            'version': packageInfo.version,
            'Content-Type': 'application/json',
            'X-User-System-ID': 'CLIENT_USER',
            'Authorization':'Bearer ' + token
        }
    },(error, response, body) => {
        if(!error && response.statusCode === 200){
            callback(body);
        }else{
            errorback(error);
        }
    })
}

function post(url,data,token,callback,errorback){
    request({
        url:config.SERVER.HOST + url,
        method:'POST',
        headers:{
            'version': packageInfo.version,
            'Content-Type': 'application/json',
            'X-User-System-ID': 'CLIENT_USER',
            'Authorization':'Bearer ' + token
        },
        body:data
    },(error, response, body) => {
        if(!error && response.statusCode === 200){
            callback(body);
        }else{
            errorback(error);
        }
    })
}

function matchStaticSourceUrl(str){
    return staticSource.includes(getUrlType(str));
}

function getUrlType(str) {
    let urlObj = url.parse(str);
    let pathname = urlObj.pathname;
    let type = pathname.split('.');
    if(!type || type.length === 0){
        return false;
    }
    return type[type.length - 1];
}

function getUrlProtocol(str) {
    let urlObj = getUrlObject(str);
    return urlObj.protocol;
}

function getUrlContentType(str){
    return contentType[getUrlType(str)];
}

function getUrlObject(str) {
    return url.parse(str);
}

function getUrlHostName(str) {
    let urlObj = getUrlObject(str);
    return urlObj.hostname;
}

function md5Crypto(password){
    const hash = crypto.createHash('md5');
    hash.update(password);

    return hash.digest('hex');
}

module.exports = {
    base64Encode:base64Encode,
    get:get,
    post:post,
    matchStaticSourceUrl:matchStaticSourceUrl,
    getUrlContentType:getUrlContentType,
    md5Crypto:md5Crypto,
    getUrlType:getUrlType,
    getUrlProtocol:getUrlProtocol,
    getUrlHostName:getUrlHostName
};
